package com.bq.gametrade.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.adapter.TradingBuyAdapter;
import com.bq.gametrade.adapter.TradingSellAdapter;
import com.bq.gametrade.base.BaseFragment;
import com.bq.gametrade.bean.Announcement;
import com.bq.gametrade.bean.HomeTradingBean;
import com.bq.gametrade.bean.HomeTradingBuy;
import com.bq.gametrade.bean.HomeTradingSell;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UpdateUserInfo;
import com.bq.gametrade.bean.UpdateUserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.activity.LoginActivity;
import com.bq.gametrade.ui.activity.MainActivity;
import com.bq.gametrade.ui.activity.RechargeActivity;
import com.bq.gametrade.ui.activity.SetPayPasswordActivity;
import com.bq.gametrade.ui.dialog.CustomerServiceDialog;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.ui.dialog.UpdateAppDialog;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.utils.SystemUtils;
import com.bq.gametrade.utils.ToastUtils;
import com.bq.gametrade.view.PayPasswordValidationView;
import com.bq.gametrade.widget.PromptAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Feel on 2016/11/24 15:28
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {


    private MainActivity activity;
    private ImageView ivService;
    //控件
    private TextView tvMarquee, tvVouchers, tvBalanceMoney;
    private CheckBox cbAreCancelled;
    private EditText edVouchersCount, edPayMoney;
    private ImageView ivUserSell, ivUserBuy, ivRefresh;

    private ListView listViewBuy, listViewSell;

    private TradingBuyAdapter buyAdapter;
    private TradingSellAdapter sellAdapter;
    private ArrayList<HomeTradingBuy> listBuy = new ArrayList<>();
    private ArrayList<HomeTradingSell> listSell = new ArrayList<>();
    private InputMethodManager inputMethodManager;
    private LoadingProgressDialog progressDialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
        progressDialog = new LoadingProgressDialog(activity,"正在支付···");

        inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        initView(root);
        getNnouncement();
        getList();

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        setData();
        updateAppVersion();
    }


    private void initView(View view) {
        ivService = (ImageView) view.findViewById(R.id.iv_userService);
        ivService.setOnClickListener(this);
        ivRefresh = (ImageView) view.findViewById(R.id.iv_refresh);
        ivRefresh.setOnClickListener(this);
        tvMarquee = (TextView) view.findViewById(R.id.tv_marquee);
        tvVouchers = (TextView) view.findViewById(R.id.tv_vouchers);
        tvBalanceMoney = (TextView) view.findViewById(R.id.tv_balanceMoney);
        tvMarquee.setSelected(true);

        edVouchersCount = (EditText) view.findViewById(R.id.ed_vouchersCount);
        edPayMoney = (EditText) view.findViewById(R.id.ed_payMoney);
        ivUserSell = (ImageView) view.findViewById(R.id.iv_userSell);
        ivUserSell.setOnClickListener(this);
        ivUserBuy = (ImageView) view.findViewById(R.id.iv_userBuy);
        ivUserBuy.setOnClickListener(this);

        listViewBuy = (ListView) view.findViewById(R.id.listView_buy);
        listViewSell = (ListView) view.findViewById(R.id.listView_sell);

    }

    private void setData() {
        if (application.isLogin()) {
            tvVouchers.setText(application.getUserInfo().userCard);
            tvBalanceMoney.setText(application.getUserInfo().userMoney);
        } else {
            tvVouchers.setText("未登录");
            tvBalanceMoney.setText("未登录");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_userService:
                CustomerServiceDialog dialog = new CustomerServiceDialog();
                dialog.show(getFragmentManager(), "show");
                break;
            case R.id.iv_userSell:
                if (!application.isLogin()) {
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("您还没有登录！")
                            .setPositiveButton("登录", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(getActivity(), LoginActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    return;
                }
                if (TextUtils.isEmpty(edVouchersCount.getText().toString())) {
                    ToastUtils.showToast(activity, "劵数量未输入");
                    return;
                }
                if (Integer.parseInt(edVouchersCount.getText().toString())<1) {
                    ToastUtils.showToast(activity, "劵数量输入不正确");
                    return;
                }

                if (TextUtils.isEmpty(edPayMoney.getText().toString())) {
                    ToastUtils.showToast(activity, "价格未输入");
                    return;
                }
                if (Integer.parseInt(edPayMoney.getText().toString())<1) {
                    ToastUtils.showToast(activity, "价格输入不正确");
                    return;
                }

                if (!NetworkUtils.isNetworkAvailable(activity)) {
                    ToastUtils.showToast(activity, "没有网络哦！");
                    return;
                }
                if (Double.parseDouble(edVouchersCount.getText().toString()) > Double.parseDouble(application.getUserInfo().userCard)) {
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示")
                            .setMsg("您还没有这么多鱼券！快去购买吧？")
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
//                                    startActivity(new Intent(getActivity(), RechargeActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    return;
                }
                if (application.getUserInfo().pay_pass.equals("1")) {
                    inputMethodManager.hideSoftInputFromWindow(edPayMoney.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    /**卖： 类型：1*/
                   toPay(1);
                } else {
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("您还没有设置支付密码？现在去设置")
                            .setPositiveButton("去设置", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(getActivity(), SetPayPasswordActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                }
                break;
            case R.id.iv_userBuy:
                if (!application.isLogin()) {
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("您还没有登录！")
                            .setPositiveButton("登录", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(getActivity(), LoginActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    return;
                }
                if (TextUtils.isEmpty(edVouchersCount.getText().toString())) {
                    ToastUtils.showToast(activity, "劵数量未输入");
                    return;
                }
//                if (TextUtils.isEmpty(edVouchersCount.getText().toString())) {
//                    ToastUtils.showToast(activity, "劵数量未输入");
//                    return;
//                }
                if (Double.parseDouble(edVouchersCount.getText().toString())<1.00) {
                    ToastUtils.showToast(activity, "劵数量输入不正确");
                    return;
                }
                if (TextUtils.isEmpty(edPayMoney.getText().toString())) {
                    ToastUtils.showToast(activity, "价格未输入");
                    return;
                }
                if (Double.parseDouble(edPayMoney.getText().toString())<1) {
                    ToastUtils.showToast(activity, "价格输入不正确");
                    return;
                }
                if (!NetworkUtils.isNetworkAvailable(activity)) {
                    ToastUtils.showToast(activity, "没有网络哦！");
                    return;
                }
                if (Double.parseDouble(edPayMoney.getText().toString()) > Double.parseDouble(application.getUserInfo().userMoney)) {
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示")
                            .setMsg("您还没有这么多钱！快去充值吧？")
                            .setPositiveButton("充值", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(getActivity(), RechargeActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    return;
                }
                if (application.getUserInfo().pay_pass.equals("1")) {
                    inputMethodManager.hideSoftInputFromWindow(edPayMoney.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    /**买： 类型：0*/
                    toPay(0);
                } else {
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("您还没有设置支付密码？现在去设置")
                            .setPositiveButton("去设置", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(getActivity(), SetPayPasswordActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                }

                break;

            case R.id.iv_refresh:
                getList();
                break;
        }
    }


    /**
     * 验证支付密码-----start
     */

    private void toPay(final int type){
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(activity,application.getUserInfo(),progressDialog);
        payPasswordValidationView.showAtLocation(activity.findViewById(R.id.fragment_home),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    toBuyOrSell(type);
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog(){
        if(progressDialog !=null){
            progressDialog.dismiss();
        }
    }


    private void getList() {
        Map<String, String> params = new HashMap<>();
        showSpotsDialog();
        VRHttp.getSellingList(getActivity(), HttpLink.HONE_SELLING_LIST_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if (response != null) {
                    ivRefresh.setVisibility(View.GONE);
                    HomeTradingBean homeTradingBean = (HomeTradingBean) response;
                    listBuy = homeTradingBean.buy;
                    listSell = homeTradingBean.sale;
                    initBuyListView(listBuy, listSell);
                }else {
                    ivRefresh.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                closeSpotsDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }

    private void getNnouncement() {
        VRHttp.getAnnouncement(getActivity(), HttpLink.HOME_ANNOUNCEMENT_URL, null, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    Announcement announcement = (Announcement) response;
                    if (announcement.status.equals("0")) {
                        tvMarquee.setText(new String(Base64.decode(announcement.msg.getBytes(), 0, announcement.msg.length(), Base64.DEFAULT)));
                    }
                }

            }
        });
    }

    /**
     * 0 :买
     * 1：卖
     *
     * @param type
     */
    private void toBuyOrSell(int type) {
        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        params.put("type", String.valueOf(type));
        params.put("num", edVouchersCount.getText().toString());
        params.put("money", edPayMoney.getText().toString().replace(",",""));
        VRHttp.sendRequest(getActivity(), HttpLink.BUYORSELL_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        ToastUtils.showToast(getActivity(), "发布成功");
                        getList();
                        if (application.isLogin()) {
                            getUserInfo();
                        }
                        getNnouncement();
                    } else {
                        ToastUtils.showToast(getActivity(), "挂单失败");
                    }
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                ToastUtils.showToast(getActivity(), "挂单失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });
    }

    private void initBuyListView(ArrayList<HomeTradingBuy> buyList, ArrayList<HomeTradingSell> sellList) {
        buyAdapter = new TradingBuyAdapter(activity, buyList);
        listViewBuy.setAdapter(buyAdapter);
        sellAdapter = new TradingSellAdapter(activity, sellList);
        listViewSell.setAdapter(sellAdapter);
    }


    private void getUserInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        VRHttp.updateUserInfo(getContext(), HttpLink.GET_USERINFO_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                UpdateUserInfo userInfo = (UpdateUserInfo) response;
                if (userInfo.status.equals("0")) {
                    UpdateUserInfoDetails userInfoDetails = userInfo.userinfo;
                    application.getUserInfo().account = userInfoDetails.telNum;
                    application.getUserInfo().userMoney = userInfoDetails.userMoney;
                    application.getUserInfo().userCard = userInfoDetails.userCard;
                    tvBalanceMoney.setText(application.getUserInfo().userMoney);
                    tvVouchers.setText(application.getUserInfo().userCard);
                } else {
                    ToastUtils.showToast(getActivity(),"登录超时请重新登陆");
                    application.setUserInfo(null);
                    startActivity(new Intent(getActivity(),LoginActivity.class));
                }

            }
        });
    }


    private void updateAppVersion() {
        final int appVersionCode = SystemUtils.getVersionCode(getActivity());
        VRHttp.getResponse(getActivity(), HttpLink.GET_APPVERSION_URL, null, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                try {
                   JSONObject object = new JSONObject(response.toString());
                    JSONObject jsonObject = object.getJSONObject("android");
                    if (jsonObject != null) {
                        boolean isForcedUpdate = jsonObject.getBoolean("forceupdate");
                        String updateContent = jsonObject.getString("text");
                        if (Integer.parseInt(jsonObject.getString("verCode")) > appVersionCode) {
                            UpdateAppDialog dialog = new UpdateAppDialog();
                            Bundle bundle = new Bundle();
                            bundle.putString("updateAppUrl", HttpLink.APP_DOWNLOAD_URL);
                            bundle.putBoolean("isForcedUpdate", isForcedUpdate);
                            bundle.putString("text", updateContent);
                            dialog.setArguments(bundle);
                            dialog.show(getFragmentManager(), "");

                        } else {

                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }

}
